package rs.pnv.pcc.handler;

import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.ws.handler.LogicalHandler;
import javax.xml.ws.handler.LogicalMessageContext;
import javax.xml.ws.handler.MessageContext;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import rs.pnv.pcc.handler.crypto.Decrypt;
import rs.pnv.pcc.handler.crypto.Encrypt;
import rs.pnv.util.DocumentUtil;

public class CryptoHandler implements LogicalHandler<LogicalMessageContext> {

	@Override
	public boolean handleMessage(LogicalMessageContext context) {

		System.out.println("CryptoHandler.handleMessage()");

		Boolean isResponse = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

		Source source = context.getMessage().getPayload();
		try {
			System.out.println("Received crypted message: ");
			DocumentUtil.printSource(source);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Document document = DocumentUtil.convertToDocument((DOMSource)source);

		if (isResponse) {
			System.out.println("kriptovanje...");
			/*
			Element element =  (Element) document.getElementsByTagNameNS("http://pcc.pnv.rs/", "Signature").item(0);  
			String certificateLocation = element.getNodeValue();
			
			Document encryptedDoc = Encrypt.encrypt(document, certificateLocation);			
			context.getMessage().setPayload(new DOMSource(encryptedDoc));
			 */
			return true;
		} else {
			System.out.println("dekriptovanje...");	
			
			//Document decryptedDoc = Decrypt.decrypt(document);
			//context.getMessage().setPayload(new DOMSource(decryptedDoc));
			
			return true;
		}

	}

	@Override
	public boolean handleFault(LogicalMessageContext context) {

		// ako vraća false, znači da NE treba da se pozove handleFault metoda od sledećeg handler-a.
		// dakle, vratiti true, ako POSTOJI greška.
		return true;
	}

	@Override
	public void close(MessageContext context) {

	}

}
